package main;

import java.util.ArrayList;

import lex.Scanner;
import parser.DrawTree;
import parser.Parser;
import parser.RecursiveDescent;
import semantic.SemanticAnalysis;
import common.Node;
import common.TreeNode;

public class Analysis {

	/**
	 * 词法分析
	 * @param path
	 * @throws Exception
	 */
	private void lexAna(String path) throws Exception {

		Scanner scanner = new Scanner();
		ArrayList<Node> nodeList = scanner.getTokenList(path);

		System.out.println("单词个数:" + nodeList.size());

		for (Node node : nodeList) {
			System.out.println("行号:" + node.getLine() + "--内容:"
					+ node.getData() + "--单词类型:" + node.getType());
		}
	}

	/**
	 * 语法分析 递归下降
	 * @param path
	 */
	private void parseRecuAna(String path) {
		TreeNode root = new TreeNode();

		RecursiveDescent parser = new RecursiveDescent(path);
		

		root = parser.program();
		if (root != null) {
			DrawTree.drawtree(root);
		}

	}
	/**
	 * 语法分析 LL(1)
	 * @param path
	 * @throws Exception 
	 */
	private void parseAna(String path) throws Exception {
		TreeNode root = new TreeNode();
		
		Parser parser = new Parser();
		root = parser.getTree1(path);
		
		if (root != null) {
			DrawTree.drawtree(root);
		}
		
	}
	
	/**
	 * 语义分析
	 * @param path
	 * @throws Exception
	 */
	private void semanticAna(String path) throws Exception {
		TreeNode root = new TreeNode();

		Parser parser = new Parser();
		root = parser.getTree1(path);

		SemanticAnalysis sa = new SemanticAnalysis();

		sa.Program(root);

		System.out.println("恭喜!您的程序无语义错误!");
	}

	public static void main(String[] args) {
		try {

			String path = System.getProperty("user.dir");
			path = path.replace("\\", "/");

			for (String str : args) {
				System.out.println(str);
			}

			Analysis analysis = new Analysis();

			switch (args[0]) {
			case "-l":
				// 词法分析
				analysis.lexAna(path + "/src/" + args[1]);
				break;

			case "-pr":
				// 语法 递归下降法
				analysis.parseRecuAna(path + "/src/" + args[1]);
				break;

			case "-p":
				
				// 语法 LL(1)
				analysis.parseAna(path + "/src/" + args[1]);
				break;
			case "-s":
				// 语义分析
				analysis.semanticAna(path + "/src/" + args[1]);
				break;

			default:
				System.out.println("参数配置错误!");

			}

		} catch (Exception e) {
			System.out.println("文件不存在....");
			//e.printStackTrace();
		}

		// System.out.println(Enum.charType.DIGIT.ordinal());
	}
}
